<template>
  <el-card class="base-card">
    <el-container class="list-layout" style="height: 100%;">
      <!-- 搜索区域 - Header -->
      <el-header class="list-header" ref="HeaderHeight">
        <el-form label-position="right" label-width="80px" :model="questionForm" class="form-layout">
          <el-form-item label="问题:" v-if="!info.addPermissions">
            <el-input v-model="questionForm.addQuestion" style="width: 100%" :disabled=info.addPermissions
              placeholder="请输入要添加的问题：请将题目全文复制，不要落下题目中的每一个中文汉字，系统会自动删除其他无关符号，只保留中文、英文、数字"></el-input>
          </el-form-item>
          <el-form-item label="答案:" v-if="!info.addPermissions">
            <el-input v-model="questionForm.addAnswer" style="width: 100%" :disabled=info.addPermissions
              placeholder="请输入要添加的问题的答案：提示：只填答案就行，例如：【A.光年】  只填【光年】就行"></el-input>
          </el-form-item>
          <el-form-item label="类型:" v-if="!info.addPermissions">
            <el-select v-model="questionForm.addType" placeholder="请选择题目类型" style="width: 80%"
              :disabled=info.addPermissions>
              <el-option label="游戏" value="游戏"></el-option>
              <el-option label="百科" value="百科"></el-option>
              <el-option label="奥运" value="奥运"></el-option>
            </el-select>
            <el-button type="primary" @click="doAdd" style="width: 20%" :disabled=info.addPermissions>添加</el-button>
          </el-form-item>

          <el-divider content-position="left">查询题库：查询到的题目有<span style="color:#ff0000">重复、不完整、答案错误</span>等任何问题,请到🐧群反馈
          </el-divider>
          <el-form-item label="问题:" style="width: 100%">
            <el-input v-model="questionForm.queryQuestion" style="width:80%" :disabled=info.queryPermissions
              placeholder="请输入问题的关键字，多个关键字请用空格隔开，例如：【光年是（）单位？】可以搜索【光年,单位】或者【光年 单位】或者【光年】或者【 单位】"></el-input>
            <el-button type="primary" @click="doQuery" style="width: 20%" :disabled=info.queryPermissions>查询</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main class="list-main" ref="MainHeight">
        <el-table :data="tableData" stripe border style="width: 100%" :style="{ height: `${tableMaxHeight}px` }">
          <el-table-column prop="id" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="type" label="类型" width="80" align="center">
          </el-table-column>
          <el-table-column prop="question" label="题目" align="center">
          </el-table-column>
          <el-table-column prop="answer" label="答案" align="center">
          </el-table-column>

          <el-table-column prop="author" width="120" label="好心人" align="center">
            <template #default="{ row }">
              <span v-if="row.author === null" style="color: green">好心人</span>
              <span v-else style="color: green">{{ row.author }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="state" label="审核状态" width="80" align="center">
            <template #default="{ row }">
              <i v-if="row.state === true" class="el-icon-circle-check" style="font-size: 20px;color:green"></i>
              <i v-else-if="row.state === false" class="el-icon-loading" style="font-size: 20px;color:red"></i>
              <i v-else class="el-icon-loading" style="font-size: 20px;color:red"></i>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer class="list-footer" ref="FooterHeight">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          @next-click="handleNextClick" @prev-click="handlePrevClick" :current-page.sync="page" background
          layout="sizes, prev, pager, next,jumper,total" :page-size="20" :page-sizes="[10, 20, 50, 100]" :total="total">
        </el-pagination>
      </el-footer>
    </el-container>
  </el-card>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, onUnmounted } from 'vue'

import apiClient from '@/utils/axios'
import { ElMessage } from 'element-plus'

interface QuestionForm {
  addQuestion: string
  addAnswer: string
  addType: string
  addAuthor: string
  queryQuestion: string
}

interface InfoState {
  addPermissions: boolean
  queryPermissions: boolean
  roles: string
  weeks: number
}

interface QuestionRow {
  id: number
  type: string
  question: string
  answer: string
  author: string | null
  state: boolean | null
}

const questionForm = reactive<QuestionForm>({
  addQuestion: '',
  addAnswer: '',
  addType: '百科',
  addAuthor: '',
  queryQuestion: '',
})

const info = reactive<InfoState>({
  addPermissions: true,
  queryPermissions: true,
  roles: '白嫖',
  weeks: 0,
})

const tableData = ref<QuestionRow[]>([])
const total = ref<number>(0)
const page = ref<number>(1)
const pageSize = ref<number>(20)

// 头部、主体、底部分区 DOM 引用
const HeaderHeight = ref<any>(null)
const MainHeight = ref<any>(null)
const FooterHeight = ref<any>(null)

// 表格最大高度，随窗口尺寸自适应
const tableMaxHeight = ref<number>(200)

const calculateTableMaxHeight = () => {
  const viewportHeight = window.innerHeight
  console.log("视窗高度", viewportHeight)

  const headerH = HeaderHeight.value?.$el?.offsetHeight ?? 0
  console.log("头部高度", headerH)

  const footerH = FooterHeight.value?.$el?.offsetHeight ?? 0
  console.log("底部高度", footerH)

  const navH = 60
  const availableHeight = viewportHeight - 20 - navH - headerH * 2   - footerH
  console.log("可用高度", availableHeight)

  tableMaxHeight.value = Math.max(availableHeight, 300)
}

const handleResize = () => {
  calculateTableMaxHeight()
}

const getTableData = () => {
  apiClient({
    url: '/user/get_question_list',
    method: 'get',
    params: {
      page: page.value,
      pageSize: pageSize.value,
    },
  })
    .then((result: any) => {
      if (result.data.status === 200) {
        total.value = result.data.data.total
        tableData.value = result.data.data.rows
      } else {
        ElMessage({
          message: result.data.msg,
          type: 'error',
          placement: 'top-right',
        })
      }
    })
    .catch((err: any) => {
      ElMessage({
        message: String(err),
        type: 'warning',
        placement: 'top-right',
      })
    })
}

const doAdd = () => {
  if (isEmpty(questionForm.addQuestion) || isEmpty(questionForm.addAnswer)) {
    ElMessage({
      message: '题目或答案不能为空',
      type: 'error',
      placement: 'top-right',
    })
    return
  }
  if (isEmpty(questionForm.addAuthor) || info.roles === '白嫖' || info.weeks === 0) {
    ElMessage({
      message: '您不可以添加',
      type: 'error',
      placement: 'top-right',
    })
    return
  }
  questionForm.addQuestion = remove_symbol(questionForm.addQuestion)
  questionForm.addAnswer = remove_symbol(questionForm.addAnswer)
  apiClient({
    url: '/user/add_question',
    method: 'post',
    data: {
      question: questionForm.addQuestion,
      answer: questionForm.addAnswer,
      author: questionForm.addAuthor,
      type: questionForm.addType,
    },
  })
    .then((result: any) => {
      if (result.data.status === 200) {
        ElMessage({
          message: result.data.msg,
          type: 'success',
          placement: 'top-right',
        })
        getTableData()
        questionForm.addQuestion = ''
        questionForm.addAnswer = ''
      } else {
        ElMessage({
          message: result.data.msg,
          type: 'error',
          placement: 'top-right',
        })
      }
    })
    .catch((err: any) => {
      ElMessage({
        message: '未知错误' + err,
        type: 'error',
        placement: 'top-right',
      })
    })
}

const doQuery = () => {
  // 将空格替换为逗号，避免使用 replaceAll 以兼容较低 lib 设置
  questionForm.queryQuestion = questionForm.queryQuestion.split(' ').join(',')

  page.value = 1
  apiClient
    .get('/user/get_question_answer', {
      params: {
        page: 1,
        pageSize: pageSize.value,
        words: questionForm.queryQuestion,
        question: '',
      },
    })
    .then((result: any) => {
      if (result.data.status === 200) {
        total.value = result.data.data.total
        tableData.value = result.data.data.rows
        ElMessage({
          message: result.data.msg,
          type: 'success',
          placement: 'top-right',
        })
      } else {
        ElMessage({
          message: result.data.msg,
          type: 'error',
          placement: 'top-right',
        })
      }
    })
    .catch((err: any) => {
      ElMessage({
        message: String(err),
        type: 'warning',
        placement: 'top-right',
      })
    })
}

//是否为空
const isEmpty = (txt: string | undefined) => {
  return txt === undefined || txt === ''
}

//去除符号
const remove_symbol = (content: string) => {
  return content.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '')
}

//每页数量变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableData()
}

//页码变化
const handleCurrentChange = (val: number) => {
  page.value = val
  getTableData()
}

//下一页
const handleNextClick = (val: number) => {
  page.value = val
  getTableData()
}

//上一页
const handlePrevClick = (val: number) => {
  page.value = val
  getTableData()
}

onMounted(() => {
  questionForm.addAuthor = localStorage.getItem('username') || ''
  const weeks = Number(sessionStorage.getItem('weeks') || 0)
  info.weeks = weeks
  info.roles = sessionStorage.getItem('roles') || '白嫖'
  getTableData()
  calculateTableMaxHeight()
  window.addEventListener('resize', handleResize)

  if (
    weeks > 0 &&
    sessionStorage.getItem('roles') === '付费' &&
    sessionStorage.getItem('addPermissions') === 'true'
  ) {
    info.addPermissions = false
  } else {
    info.addPermissions = true
  }
  if (sessionStorage.getItem('queryPermissions') === 'true') {
    info.queryPermissions = false
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
/* ==================== 统一组件卡片样式 ==================== */
.base-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: rgba(255, 255, 255, 0.5);
}

.base-card .el-card__body {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: rgba(255, 255, 255, 0.5);
}

/* ==================== 容器样式 ==================== */
.list-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.list-layout {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* ==================== Header 区域样式 ==================== */
.list-header {
  padding: 16px;
  background-color: rgba(255, 255, 255, 0.5);
  border-bottom: 1px solid #e6e6e6;
  flex-shrink: 0;
  height: auto !important;
}

/* ==================== 搜索表单样式 ==================== */
.search-form {
  margin-bottom: 0;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 0;
}

/* ==================== Main 区域样式 ==================== */
.list-main {
  flex: 1;
  overflow: hidden;
  padding: 0;
  display: flex;
  flex-direction: column;
  min-height: 0;
  background-color: rgba(255, 255, 255, 0.5);
}

.table-container-wrapper {
  flex: 1;
  padding: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

/* ==================== Footer 区域样式 ==================== */
.list-footer {
  height: 60px !important;
  /* padding: 10px; */
  display: flex;
  justify-content: flex-end;
  align-items: center;
  border-top: 1px solid #e6e6e6;
  flex-shrink: 0;
  background-color: rgba(255, 255, 255, 0.5);
}

/* ==================== 重置 Element Plus Container 的默认样式 ==================== */
.list-layout .el-main {
  padding: 0;
}

.list-layout .el-footer {
  padding-bottom: 5px;
}

/* ==================== 表格样式 ==================== */
.el-table {
  font-size: 14px;
  background-color: rgba(255, 255, 255, 0.5);
}

/* 表格样式 - 确保所有单元格内容居中 */
.el-table th,
.el-table td {
  text-align: center !important;
}

.el-table .cell {
  text-align: center !important;
  justify-content: center !important;
}

/* 确保操作列按钮对齐 */
.el-table .el-button {
  margin: 0 2px;
}

/* ==================== 常用表单组件半透明 ==================== */
/* .el-input__inner,
.el-textarea__inner {
  background-color: rgba(255, 255, 255, 1) !important;
}

.el-select,
.el-select .el-input__inner {
  background-color: rgba(255, 255, 255, 1) !important;
}

.el-button {
  background-color: rgba(255, 255, 255, 1) !important;
} */

.el-pagination.is-background .el-pager li,
.el-pagination.is-background .btn-prev,
.el-pagination.is-background .btn-next,
.el-pagination__jump {
  background-color: rgba(255, 255, 255, 0.5) !important;
}

/* ==================== 响应式设计 ==================== */
@media (max-width: 768px) {
  .search-form {
    justify-content: flex-start;
  }

  .list-header {
    padding: 12px;
  }

  .list-footer {
    padding: 8px;
  }
}
</style>